package com.happe.foodeasy.controller.index;

import com.alibaba.fastjson.JSON;
import com.happe.foodeasy.dto.PositionImageDTO;
import com.happe.foodeasy.service.ImgService;
import com.happe.foodeasy.util.ImgPositionEnum;
import com.happe.foodeasy.util.ResultEntity;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * 这个controller用于处理图片的请求
 * Created by wubin on 2016-12-04.
 */
@Controller
@RequestMapping("/img")
public class IndexImgController {
    private Logger logger = LoggerFactory.getLogger(IndexImgController.class);

    @Resource
    private ImgService imgService;

    /**
     * 用于获得主页轮播图的图片id数组，使用response发回json。
     *
     * @param response HttpServletResponse
     */
    @RequestMapping("/selectCarouselImgInfo")
    public void selectCarouselImgInfo(HttpServletResponse response) {
        List<PositionImageDTO> indexCarouselImg = imgService.selectTargetPositionImgInfo(ImgPositionEnum.INDEX_POSITION.idValue());
        long[] resultArr = new long[indexCarouselImg.size()];
        for (int i = 0; i < indexCarouselImg.size(); i++) {
            resultArr[i] = indexCarouselImg.get(i).getId();
        }

        String jsonResult = JSON.toJSONString(new ResultEntity(resultArr));
        try {
            response.getWriter().write(jsonResult);
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
    }

    /**
     * 将对应的imageId的图片的文件流发回客户端
     *
     * @param imageId  目标image的id
     * @param response HttpServletResponse
     */
    @RequestMapping("/selectCarouselImg")
    public void selectCarouselImg(Integer imageId, HttpServletResponse response) {
        InputStream in = imgService.selectTargetPositionImg(imageId);
        try {
            IOUtils.copy(in, response.getOutputStream());
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
    }
}
